from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from django.template.context_processors import request
#from pyqrcode.tables import modes
from django.http import JsonResponse
from .models import Wenzhang,Grjj,Like,Banner,Link,Fenlei,Ly,Mryj,Shoucang
from PIL import  Image
import  re
from django.db import connection
from django.contrib.auth.decorators import login_required
from django.db.models import Count, Q
import json

def base(request):
    return render(request, 'base.html')


def hello(request):
    return render(request, 'index.html')

def panduan(request):
    dl_user=request.user #获取登录用户
    print(dl_user)
    if not request.user.is_authenticated:  #没有用户登录
        dl_user='1'#就读取用户0的文章
    else: #如果用户已经登录
        dl_user=request.user
    return dl_user

def w_user(request):
    dl_user=request.user #获取登录用户
    #print(dl_user)
    if not request.user.is_authenticated:  #没有用户登录
        dl_user='游客'
    else: #如果用户已经登录
        dl_user=request.user
    return dl_user


# def banner(request):
#     #user=panduan()  #本来可以为每位用户添加轮转图，但是找图片裁剪太麻烦，只显示管理员的图片，这段就放到全局里
#     ban=Banner.objects.filter(user=user,is_active=True)[0:3]#查询所有幻灯图数据，并进行切片
#     return render(request, 'index.html', context)

def hot(request):
    #print('hot')
    user=panduan(request)
    print(user)
    hot=Wenzhang.objects.filter(user=user).values('id','title','views').order_by('views')[0:5]# 查询数据，并进行切片
    print(hot)
    data=json.dumps(list(hot))
    return HttpResponse(data)

#转换工具，可以将自定义SQL的查询结果转换为字典，发送到前台模板。
def dictfetchall(cursor):
    "从cursor获取所有行数据转换成一个字典"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]


#右侧页面信息获取,以及全局信息获取
def global_right_html(request):
    dl_user = request.user  # 获取登录用户
    # print(dl_user)
    if not request.user.is_authenticated:  # 没有用户登录
        dl_user = '游客'
    else:  # 如果用户已经登录
        dl_user = request.user
    #显示banner
    ban = Banner.objects.filter(is_active=True).order_by('-id')[0:3]  # 查询所有幻灯图数据，并进行切片

    # 查询热门文章,ID,标题，和用户浏览数
    hot = Wenzhang.objects.all().values('id', 'title', 'views').order_by('-views')[0:5]  # 查询所有 数据，并进行切片

    # 点赞文章，自定义SQL查询文章ID,标题，并关联到子表分别查询点赞数量，倒序，取前10
    dz_wz = Wenzhang.objects.raw(
        'SELECT a.id as id,a.title as title,b.dz as dz from blog_wenzhang a,(SELECT wz_id,COUNT(*) as dz FROM `blog_like` GROUP BY wz_id ORDER BY COUNT(*) DESC LIMIT 10)b where a.id=b.wz_id')

    # 友情链接，查询友情链接，根据ID取5个展示到前台。
    yq_link = Link.objects.all().order_by('-id')[0:5]  # 查询所有

    #每日一句
    mr_yj=Mryj.objects.values('yiju').order_by('?')[:1]   #随机选取一条

    # 文章归档，完全不用Django的内置模型，编写SQL语句，将文章按日期归档
    sql = '''SELECT  date_format(`created_time`,'%Y-%m') as sj,COUNT(*) as sl  FROM `blog_wenzhang`  GROUP BY date_format(`created_time`,'%Y-%m') ORDER BY 1 DESC'''
    with connection.cursor() as cursor:
        cursor.execute(sql)  # 执行归档语句
        row = dictfetchall(cursor)  # 用上方写的工具，将其转换为字典
    wz_gd = row

    return locals()

#首页文章展示，网站首页
def index(request):
    dl_user = request.user  # 获取登录用户
    # if not request.user.is_authenticated:  # 没有用户登录
    #     wz = Wenzhang.objects.annotate(Count('like', )).all().order_by('-id')[0:10]
    # else:  # 如果用户已经登录
    #     dl_user = request.user
    #     wz = Wenzhang.objects.annotate(Count('like', )).filter(Q(user=dl_user)|Q(user='1')).order_by('-id')[0:10]
    #首页修改为显示所有文字，文章列表改为我的文章列表
    wz = Wenzhang.objects.annotate(Count('like', )).all().order_by('-id')[0:10]
    #将查询数据发送到前台页面index.html渲染
    #return render(request,'index.html',{'wz': wz,'hot':hot,'dl_user':dl_user,'dz_wz':dz_wz,'info':"欢迎来到我的博客",'yq_link':yq_link,'wz_gd':wz_gd})
    return render(request, 'index.html', locals())


#文章正文查看
def read(request):
    wz_id=request.GET.get('id')   #获取前台发送的参数
    wz_zw=Wenzhang.objects.get(id=wz_id)  #根据前台参数查询数据库
    user=w_user(request)
    wz_zw.views+=1            #将文章浏览数+1
    wz_zw.save()              #保存
    return render(request, 'read.html', context={'article': wz_zw})

#点赞功能
def like(request):
    take_data = request.GET     #获取前台传递的系列参数
    wz_id=take_data['id']     #将获取的参数取出ID
    act=take_data['action']   #取出ACTION
    print(act,wz_id)
    send_data={}             #准备发送到前台的数据
    user=request.user
    if act=='like':          #如果ACTION 是like动作  点赞动作
        Like.objects.create(wz_id=wz_id,user=user)  # 将点赞的文章ID和点赞人姓名插入blog_Like表
        like_number=len(Like.objects.filter(wz_id=wz_id)) #查询当前文章点赞数
        send_data['status']='success'                #构造发送数据状态
        send_data['like_number']=like_number         #填写发送点赞数
        send_data['message']='dzcg'
    elif act=='sc': #如果ACTION 是收藏动作
        Shoucang.objects.create(wz_id=wz_id,user=user)  # 将 插入
        #like_number=len(Shoucang.objects.filter(wz_id=wz_id)) #查询当前文章点赞数
        send_data['status']='success'                #构造发送数据状态
        #send_data['like_number']=like_number         #填写发送点赞数
        send_data['message']='sccg'#收藏成功

    return JsonResponse(send_data)                    #将数据以JSON的类型发送到前台的AJAX解析

#收藏页面展示
def dzsc(request):
    dl_user=str(request.user) #获取登录用户
    print(dl_user)
    info=''
    if not request.user.is_authenticated:  #用户没有登录
        dzsc_wz=Wenzhang.objects.raw("SELECT a.* FROM `blog_wenzhang` a WHERE id in(SELECT DISTINCT wz_id FROM `blog_shoucang`) ")
    else: #如果用户已经登录
        dzsc_wz=Wenzhang.objects.raw("SELECT a.* FROM `blog_wenzhang` a,`auth_user` c WHERE a.user_id=c.id and a.id in(SELECT DISTINCT b.wz_id FROM `blog_shoucang` b where b.user=%s) and c.username<>%s",[dl_user,dl_user])
        if len(dzsc_wz)==0:
            info="你还没有收藏"
        else:
            info="你的收藏如下"
    return render(request, 'wz_liebiao.html', context={'wz_lb': dzsc_wz,'info':info})

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger    #引入Django 内置分页
#@login_required(login_url='/accounts/login/')
def wz_liebiao(request):
    current_page = request.GET.get('page')  #获取前台分页参数
    dl_user=w_user(request)
    if dl_user=="游客":
        wz_lb=Wenzhang.objects.all().order_by('-id') #如果没有登录展示所有的文章列表
    else:
        wz_lb=Wenzhang.objects.filter(Q(user=dl_user)|Q(user='1')).order_by('-id')  #展示当前用户文章列表
    paginator = Paginator(wz_lb, 10)  # 实例化一个分页对象, 每页显示10个
    try:
        posts = paginator.page(current_page)
        # has_next              是否有下一页
        # next_page_number      下一页页码
        # has_previous          是否有上一页
        # previous_page_number  上一页页码
        # object_list           分页之后的数据列表
        # number                当前页
        # paginator             paginator对象
    except PageNotAnInteger:
        posts = paginator.page(1)   #没有当前页面就展示页码1
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)
    return render(request, 'wz_liebiao.html', {'wz_lb': posts})

#文章归档 查看
def wz_gdlb(request):
    dl_user=request.user
    if request.GET.get('rq'):    #GET前台点击的日期
        rq=request.GET.get('rq')
        t=rq.split('-',1) #分割时间
        y=int(t[0])   #年
        m=int(t[1])   #月
        #print(y,m)
        wz_gd=Wenzhang.objects.filter(created_time__year=y,
                                      created_time__month=m).order_by('-id')
        paginator = Paginator(wz_gd, 10)  # 实例化一个分页对象, 每页显示10个
        try:
            posts = paginator.page(1)  # 展示页码1
        except EmptyPage:
            posts = paginator.page(paginator.num_pages)
        return render(request, 'wz_liebiao.html', {'wz_lb': posts,'info':rq+'月的文章归档'})

#留言板功能
def liuyanban(request):
    if(request.method == 'POST'):  #如果前台是POST发送的数据
        name=request.POST.get('name').strip()  #获取留言人name
        comment=request.POST.get('comment').strip()#获取留言
        #print(name,comment)
        Ly.objects.create(name=name,say=comment) #留言写入数据库

        #print(dl_user)
    current_page = request.GET.get('page')  #获取分页参数
    ly_all=Ly.objects.all().order_by('-id') #展示所有
    paginator = Paginator(ly_all, 10)  # 实例化一个分页对象, 每页显示10个
    try:
        posts = paginator.page(current_page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)
    return render(request, 'ly.html', {'ly_all':posts})


# 搜索功能
def search(request):
    current_page = request.GET.get('page')  # 获取分页参数
    print(current_page)
    dl_user = w_user(request)
    if request.method == 'POST':  #接受到查询参数
        keyword=request.POST['keyword']
    wz_lb = Wenzhang.objects.filter(title__icontains=keyword).order_by('-id')
    paginator = Paginator(wz_lb, 3)  # 实例化一个分页对象, 每页显示10个
    try:
        posts = paginator.page(current_page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)

    if len(wz_lb)==0:
        info='你查询的关键字%s没有结果'%keyword
    else:
        info='你重新的关键字%s结果如下'%keyword
    return render(request, 'wz_liebiao.html', {'wz_lb': posts, 'info': info})
#生活笔记
def shbj(request,s):
    if s=='sb':
        #个人随笔
        sql=''' SELECT * from blog_wenzhang where wzfenlei_id=(
SELECT id FROM `blog_fenlei` WHERE name='个人随笔')'''
    elif s=='rj':
       #个人日记
       sql = ''' SELECT * from blog_wenzhang where wzfenlei_id=(
        SELECT id FROM `blog_fenlei` WHERE name='个人日记')'''
    else:
        #个人心情
        sql = ''' SELECT * from blog_wenzhang where wzfenlei_id=(
               SELECT id FROM `blog_fenlei` WHERE name='个人心情')'''
    wz=Wenzhang.objects.raw(sql)
    if len(wz)==0:
        info='没有找到文章'
    else:
        info=''
    return render(request, 'wz_liebiao.html', {'wz_lb': wz, 'info': info})
#健康养生
def jksh(request,s):
    if s=='sl':
        #食疗养生
        sql = ''' SELECT * from blog_wenzhang where wzfenlei_id=(
        SELECT id FROM `blog_fenlei` WHERE name='食疗养生')'''
    elif s=='xl':
        #心理健康
        sql = ''' SELECT * from blog_wenzhang where wzfenlei_id=(
                SELECT id FROM `blog_fenlei` WHERE name='心理健康')'''
    else:
        sql = ''' SELECT * from blog_wenzhang where wzfenlei_id=(
                     SELECT id FROM `blog_fenlei` WHERE name='减肥生活')'''
    wz=Wenzhang.objects.raw(sql)
    if len(wz)==0:
        info='没有找到文章'
    else:
        info=''
    return render(request, 'wz_liebiao.html', {'wz_lb': wz, 'info': info})

#个人简介&联系方式
def grjj(request):
    user=panduan(request)
    gr=Grjj.objects.filter(user=user)
    return render(request, 'grjj.html', {'gr': gr,'info':'个人简介'})

